/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Servlets;

import Entidades.ObjetoAprendizajeEnt;
import Entidades.SFTPFileCopy1;
import Entidades.UsuarioEnt;
import Negocio.ObjetoAprendizajeNeg;
import Negocio.SubirFTPNeg;
import Utilidades.Constantes;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

/**
 *
 * @author usuario
 */
@WebServlet(name = "CreacionServ", urlPatterns = {"/CreacionServ"})
public class CreacionServ extends HttpServlet {

    ObjetoAprendizajeNeg negocio;
    SubirFTPNeg negSubir;
    SFTPFileCopy1 negFTP;
    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, FileUploadException {
        response.setContentType("text/html;charset=UTF-8");
        
        
        negSubir = new SubirFTPNeg();
        ObjetoAprendizajeEnt objApren = new ObjetoAprendizajeEnt();
        negocio = new ObjetoAprendizajeNeg();
        File fileObjeto;
                
        objApren.getTema().setCodigo(request.getParameter("TemaCat"));
        objApren.getAutor().setNombre(request.getParameter("Autor"));
        objApren.getAutor().setStrFechaRealizacion(request.getParameter("date"));
        objApren.setNombre(request.getParameter("NameObjeto"));
        objApren.setObjetivoGeneral(request.getParameter("ObjetivoGeneral"));
        objApren.setObjetivoEspecifico(request.getParameter("ObjetivoEspecifico"));
        objApren.setResumen(request.getParameter("Resumen"));
        objApren.setStrMetadatos(request.getParameter("Metadatos"));
        
        
        try {
                List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
                for (FileItem item : items) {
                    if (item.isFormField()) {
                        // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                        String fieldname = item.getFieldName();
                        String fieldvalue = item.getString();
                        
                        if(fieldname.equals("TemaCat")){
                            objApren.getTema().setCodigo(fieldvalue);
                        }
                         if(fieldname.equals("Tipo")){
                            objApren.setTipo(fieldvalue);
                        }
                        
                        if(fieldname.equals("Autor")){
                            objApren.getAutor().setNombre(fieldvalue);
                        }
                        if(fieldname.equals("date")){
                            objApren.getAutor().setStrFechaRealizacion(fieldvalue);
                        }
                        if(fieldname.equals("NameObjeto")){
                            objApren.setNombre(fieldvalue);
                        }
                        if(fieldname.equals("ObjetivoGeneral")){
                            objApren.setObjetivoGeneral(fieldvalue);
                        }
                        if(fieldname.equals("ObjetivoEspecifico")){
                            objApren.setObjetivoEspecifico(fieldvalue);
                        }
                        if(fieldname.equals("Resumen")){
                            objApren.setResumen(fieldvalue);
                        }
                        if(fieldname.equals("Metadatos")){
                            objApren.setStrMetadatos(fieldvalue);
                        }
  
                        // ... (do your job here)
                    } else {
                        
                        negFTP = new SFTPFileCopy1();
                        // Process form file field (input type="file").
                        String fieldname = item.getFieldName();
                        String filename = FilenameUtils.getName(item.getName());
                        InputStream filecontent = item.getInputStream();
                        
                        if(fieldname.equals("EXAMINAR")){
                        
                        byte[] buff = new byte[8000];

                        int bytesRead = 0;

                        ByteArrayOutputStream bao = new ByteArrayOutputStream();

                        while((bytesRead = filecontent.read(buff)) != -1) {
                           bao.write(buff, 0, bytesRead);
                        }

                        byte[] data = bao.toByteArray();

                        ByteArrayInputStream bin = new ByteArrayInputStream(data);
          
                       String ruta = negFTP.retornarRuta(true, filename,  bin, objApren.getNombre());
                       if (ruta.equals("null")){
                           request.getRequestDispatcher(Constantes.ERROR).forward(request, response);
                        }
                        
                       objApren.setRutaArchivo(ruta);
                        }
                        
                        if(fieldname.equals("EXAMINAR_AUTOR")){
                        
                        byte[] buff = new byte[8000];

                        int bytesRead = 0;

                        ByteArrayOutputStream bao = new ByteArrayOutputStream();

                        while((bytesRead = filecontent.read(buff)) != -1) {
                           bao.write(buff, 0, bytesRead);
                        }

                        byte[] data = bao.toByteArray();

                        ByteArrayInputStream bin = new ByteArrayInputStream(data);
          
                       String ruta = negFTP.retornarRuta(true, filename,  bin, objApren.getNombre());
                       if (ruta.equals("null")){
                           request.getRequestDispatcher(Constantes.ERROR).forward(request, response);
                        }
                       
                       objApren.setURL(ruta);
                        }
                        
                        // ... (do your job here)
                    }
                }
    } catch (FileUploadException e) {
        throw new ServletException("Cannot parse multipart request.", e);
    }
        
        
        try {
                UsuarioEnt usuarioEnt;
                usuarioEnt = (UsuarioEnt) request.getSession().getAttribute("usuarioSe");
                negocio.ingresarObjetosAprendizaje(objApren, usuarioEnt.getCodigo());
                
        } catch (SQLException ex) {
            Logger.getLogger(CreacionServ.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        request.setAttribute("creacion", 1);
        request.getRequestDispatcher(Constantes.MENSAJE_CREACION).forward(request, response);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(CreacionServ.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (FileUploadException ex) {
            Logger.getLogger(CreacionServ.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
